package util;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.text.TextUtils;
import android.util.Log;
import com.example.administrator.text.Framgnet.WiFiFragment;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuxiaobin on 2017/4/\
 * wifi 工具类
 *
 */

public class WifiUtil {

    /**
     * 定义一个WifiManager对象,提供Wifi管理的各种主要API，主要包含wifi的扫描、建立连接、配置信息等
     */
    private WifiManager mWifiManager;
    // WIFIConfiguration描述WIFI的链接信息，包括SSID、SSID隐藏、password等的设置
    private List<WifiConfiguration> wifiConfigList;
    // 定义一个WifiInfo对象
    private WifiInfo mWifiInfo;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfigurations;
    private WifiLock mWifiLock;
    private static WifiUtil mWifiUtil;
    private Context mContext;

    private WifiUtil(Context context) {
        // 获得WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
        mContext = context;
    }
    public static WifiUtil getInstance(Context context){
        if(mWifiUtil == null){
            synchronized (WifiUtil.class){
                if(mWifiUtil == null){
                    mWifiUtil = new WifiUtil(context);
                    return  mWifiUtil;
                }
            }
        }
        return mWifiUtil;
    }

    /**
     * 获取wifi名称
     */
    public String getWIFIName(){
        mWifiInfo = mWifiManager.getConnectionInfo();
        String wifiId = mWifiInfo != null ? mWifiInfo.getSSID() : null;
        String wifiName = wifiId.substring(0,wifiId.length());
        LogUtil.eE("","...wifiName...1"+wifiName);
        if(wifiName.length() >=1 ){
            if(wifiName.substring(0,1).equals("\"")){
                String wifi = wifiName.substring(1,wifiName.length()-1);
                return wifi;
            }else {
                return wifiName;
            }
        }
        return wifiName;
    }

    /**
     * 打开wifi
     */
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭wifi
     */
    public void closeWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 检查当前wifi状态
     *
     */
    public int checkState() {
        return mWifiManager.getWifiState();
    }
    /**
     * 锁定wifiLock
     */
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }
    /**
     * 解锁wifiLock
     */
    public void releaseWifiLock() {
        // 判断是否锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }
    /**
     * 创建一个wifiLock
     */
    public void createWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("test");
    }

    /**
     * 得到配置好的网络
     *
     */
    public List<WifiConfiguration> getWiFiConfiguration() {
        return mWifiConfigurations;
    }

    /**
     * 指定配置好的网络进行连接
     *
     */
    public void connetionConfiguration(int index) {
        if (index > mWifiConfigurations.size()) {
            return;
        }
        // 连接配置好指定ID的网络
        mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId,
                true);
    }
    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        // 得到配置好的网络连接
        mWifiConfigurations = mWifiManager.getConfiguredNetworks();
    }

    /**
     * 得到网络列表
     * 除去了重复的SSID
     */
    public List<ScanResult> getWifiList() {
        List<ScanResult> wifiList = new ArrayList<>();
        try {
            if(mWifiManager !=null){
                List<ScanResult> list  = mWifiManager.getScanResults();
                int size1 = list.size();
                if(list !=null){
                    for (int i = 0; i <size1; i++) {
                        if( i== 0 ){
                            wifiList.add(list.get(i));
                        }else {
                            int size2 = wifiList.size();
                            for (int j = 0; j < size2; j++) {
                                if(list.get(i).SSID.equals(wifiList.get(j).SSID)){
                                    if(list.get(i).level >= wifiList.get(j).level){
                                        wifiList.remove(j);
                                        wifiList.add(list.get(i));
                                        break;
                                    }else {
                                        break;
                                    }
                                }else {
                                    if(j == size2-1){
                                        wifiList.add(list.get(i));
                                    }
                                }
                            }
                        }
                    }
                    return newFSSID(wifiList);
                }else {
                    return null;
                }
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }


    private List<ScanResult> newFSSID(List<ScanResult> newfi){
        int nefi = 0;
        int size = newfi.size();
        for (int i = 0; i < size ; i++) {
             if(sSIDName(newfi.get(i).SSID).equals(WiFiFragment.mNewFiWiFi)){
                 nefi = i;
                 break;
             }
        }
        if(nefi == 0){
            return newfi;
        }else {
            return newFiSSID(newfi,nefi);
        }
    }
    /**
     * 把newFi 放置在第一个
     */
    private List<ScanResult> newFiSSID(List<ScanResult> newfi,int p){
        if(p>0){
            List<ScanResult> nweFiwifi = new ArrayList<>();
            nweFiwifi.add(newfi.get(p));
            int size = newfi.size();
            for (int i = 0; i <size; i++) {
                if(i !=p){
                    nweFiwifi.add(newfi.get(i));
                }
            }
            return nweFiwifi;
        }else {
            return newfi;
        }
    }

    private String sSIDName(String name){
        if(name !=null && name.length()>2){
            if(name.substring(0,1).equals("\"")){
                String wifiName = name.substring(1,name.length()-1);
                LogUtil.eE("",wifiName);
                return wifiName;
            }else {
                return name;
            }
        }else {
            return name;
        }
    }
    /**
     * 得到网络列表
     * 没有去重复的SSID
     */
    public List<ScanResult> getListScanResult() {
        return mWifiManager.getScanResults();
    }


    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    public int getIpAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    /**
     * 得到连接的ID
     *
     */
    public int getNetWordId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    /**
     * 得到wifiInfo的所有信息
     *
     */
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    /**
     * 添加一个网络并连接
     *
     */
    public void addNetwork(WifiConfiguration configuration) {
        int wcgId = mWifiManager.addNetwork(configuration);
        mWifiManager.enableNetwork(wcgId, true);
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password,
                                            WifiCipherType Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            if (!TextUtils.isEmpty(Password)) {
                if (isHexWepKey(Password)) {
                    config.wepKeys[0] = Password;
                } else {
                    config.wepKeys[0] = "\"" + Password + "\"";
                }
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wpa
        if (Type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // 此处需要修改否则不能自动重联
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }
    /**
     * 断开指定ID的网络
     *
     */
    public void disConnectionWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    /**
     * 连接指定Id的WIFI
     *
     */
    public boolean ConnectWifi(int wifiId) {
         if(wifiConfigList !=null){
             int size = wifiConfigList.size();
             for (int i = 0; i < size; i++) {
                 WifiConfiguration wifi = wifiConfigList.get(i);
                 if (wifi.networkId == wifiId) {
                     while (!(mWifiManager.enableNetwork(wifiId, true))) {// 激活该Id，建立连接
                         Log.i("ConnectWifi",
                                 String.valueOf(wifiConfigList.get(wifiId).status));// status:0--已经连接，1--不可连接，2--可以连接
                     }
                     return true;
                 }
             }
         }
        return false;
    }

    /**
     * 得到Wifi配置好的信息
     */
    public void getConfiguration() {
        mWifiManager = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);
        if(mWifiManager !=null ){
            wifiConfigList = mWifiManager.getConfiguredNetworks();// 得到配置好的网络信息
            if(wifiConfigList !=null){
                int size = wifiConfigList.size();
                for (int i = 0; i < size; i++) {
                    Log.i("getConfiguration", wifiConfigList.get(i).SSID);
                    Log.i("getConfiguration",
                            String.valueOf(wifiConfigList.get(i).networkId));
                }
            }
        }
    }

    /**
     * 判定指定WIFI是否已经配置好,依据WIFI的地址BSSID,返回NetId
     *
     */
    public int IsConfiguration(String SSID) {
        getConfiguration();
        if(wifiConfigList !=null){
            int size = wifiConfigList.size();
            for (int i = 0; i < size; i++) {
                if (wifiConfigList.get(i).SSID.equals(SSID)) {// 地址相同
                    return wifiConfigList.get(i).networkId;
                }
            }
        }
        return -1;
    }
    /**
     * 添加指定WIFI的配置信息,原列表不存在此SSID
     *
     */
    public int AddWifiConfig(List<ScanResult> wifiList, String ssid, String pwd) {
        int wifiId = -1;
        for (int i = 0; i < wifiList.size(); i++) {
            ScanResult wifi = wifiList.get(i);
            if (wifi.SSID.equals(ssid)) {
                Log.i("AddWifiConfig", "equals");
                WifiConfiguration wifiCong = new WifiConfiguration();
                wifiCong.SSID = "\"" + wifi.SSID + "\"";// \"转义字符，代表"
                wifiCong.preSharedKey = "\"" + pwd + "\"";// WPA-PSK密码
                wifiCong.hiddenSSID = false;
                wifiCong.status = WifiConfiguration.Status.ENABLED;
                wifiId = mWifiManager.addNetwork(wifiCong);// 将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态，成功返回ID，否则为-1
                if (wifiId != -1) {
                    return wifiId;
                }
            }
        }
        return wifiId;
    }

    /**
     * 定义几种加密方式，一种是WEP，一种是WPA，还有没有密码的情况
     */
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    /**
     *提供一个外部接口，传入要连接的无线网
     */
    public void connect(String ssid, String password, WifiCipherType type) {
        Thread thread = new Thread(new ConnectRunnable(ssid, password, type));
        thread.start();
    }

    class ConnectRunnable implements Runnable {
        private String ssid;

        private String password;

        private WifiCipherType type;

        public ConnectRunnable(String ssid, String password, WifiCipherType type) {
            this.ssid = ssid;
            this.password = password;
            this.type = type;
        }

        @Override
        public void run() {
            try {

                LogUtil.eE("","...............ConnectRunnable.................."+NetUtils.getInstance(mContext).getNetWorkTeyt());
                // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
                if(NetUtils.getInstance(mContext).getNetWorkTeyt() != 1){
                    while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
                        try {
                            // 为了避免程序一直while循环，让它睡个100毫秒检测……
                            Thread.sleep(100);
                        } catch (InterruptedException ie) {
                        }
                    }
                }

                LogUtil.eE("","...............ConnectRunnable..................1..."+NetUtils.getInstance(mContext).getNetWorkTeyt());
                WifiConfiguration wifiConfig = createWifiInfo(ssid, password,
                        type);
                if (wifiConfig == null) {
                    return;
                }

                WifiConfiguration tempConfig = isExsits(ssid);

                if (tempConfig != null) {
                    mWifiManager.removeNetwork(tempConfig.networkId);
                }

                int netID = mWifiManager.addNetwork(wifiConfig);
                boolean enabled = mWifiManager.enableNetwork(netID, true);
                boolean connected = mWifiManager.reconnect();
                LogUtil.eE("","...netID...1"+netID+"..enabled.."+enabled+"..connected.."+connected);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        if (len != 10 && len != 26 && len != 58) {
            return false;
        }
        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
                    && c <= 'f')) {
                return false;
            }
        }

        return true;
    }

}
